package cn.com.b2office.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.BrandDao;
import cn.com.b2office.domain.ItemBrand;

public class BrandDaoHibernateImpl extends HibernateDaoSupport implements
		BrandDao {

	public String createBrand(ItemBrand brand) {
		return (String) getHibernateTemplate().save(brand);
	}

	public ItemBrand getBrand(String brandId) {
		return (ItemBrand) getHibernateTemplate().get(ItemBrand.class, brandId);
	}

	public void removeBrand(String brandId) {
		Session s = getSession();
		try {
			ItemBrand brand = (ItemBrand) s.load(ItemBrand.class, brandId);
			s.delete(brand);
		} catch (HibernateException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
	}

	public void removeBrand(ItemBrand brand) {
		getHibernateTemplate().delete(brand);
	}

	public List<ItemBrand> findBrands(List<String> brandIdList) {
		List<ItemBrand> list = null;
		Session s = getSession();
		try {
			Criteria criteria = s.createCriteria(ItemBrand.class);
			criteria.add(Expression.eq("item_flag", "1"));
			criteria.add(Expression.eq("notshow", 0));
			criteria.add(Expression.in("brand_no", brandIdList));
			criteria.addOrder(Order.desc("sortwt"));
			// 此处启用查询缓存
			criteria.setCacheable(true);
			list = criteria.list();
		} catch (HibernateException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	public List<ItemBrand> findBrands(String[] brandIdArray) {
		List<ItemBrand> list = null;
		Session s = getSession();
		try {
			Criteria criteria = s.createCriteria(ItemBrand.class);
			criteria.add(Expression.eq("item_flag", "1"));
			criteria.add(Expression.eq("notshow", 0));
			criteria.add(Expression.in("brand_no", brandIdArray));
//			criteria.addOrder(Order.desc("sortwt"));
			// 此处启用查询缓存
			criteria.setCacheable(true);
			list = criteria.list();
		} catch (HibernateException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

}
